package com.kakavr.user.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Maps;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.kakavr.base.controller.BaseController;
import com.kakavr.base.exception.ValidateParamException;
import com.kakavr.pay.util.GainUtil;
import com.kakavr.recharge.service.IRechargeRuleService;
import com.kakavr.result.MsgResult;
import com.kakavr.result.Result;
import com.kakavr.result.constant.MsgConstants;
import com.kakavr.user.service.IUserRechargeService;
import com.kakavr.util.SessionUtils;
import com.kakavr.util.ValidatorUtils;
/**
 * 充值
 * @author gang.yang
 *
 */
@RestController
@RequestMapping("recharge")
public class UserRechargeController extends BaseController {
	@Resource
	private IUserRechargeService userRechargeService;
	@Resource
	private IRechargeRuleService rechargeRuleService;
	
	
	/**
	 * 支付宝支付
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "alipay", method = RequestMethod.POST)
	public Map<String, Object> alipay(HttpServletRequest request){
		Map<String,Object> map = this.getParam(request);
		map.put("paytype", "alipay");
		map.put("mode", 1);
		return MsgResult.okResultData(userRechargeService.addUserRechargeByAlipay(map));
	}

	/**
	 * 微信支付获取二维码
	 * @param request
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "wxpay", method = RequestMethod.GET)
	public void wxpay(HttpServletRequest request,HttpServletResponse response) throws IOException{
		Map<String,Object> map = this.getParam(request);
		map.put("spbillIp", GainUtil.getIpAddr(request));
		map.put("paytype", "wxpay");
		map.put("mode", 0);
		String codeUrl = userRechargeService.addUserRechargeByWXpay(map);
		if(StringUtils.isBlank(codeUrl)){
			Result.outJson("参数异常", response);
		}
		Map<EncodeHintType, Object> hints = Maps.newHashMap();
		// 指定纠错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
        // 指定编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        hints.put(EncodeHintType.MARGIN, 1);
        OutputStream out = null;
        try {
			BitMatrix bitMatrix = new MultiFormatWriter().encode(codeUrl, BarcodeFormat.QR_CODE, 500, 500, hints);
			out = response.getOutputStream();
            MatrixToImageWriter.writeToStream(bitMatrix, "png", out);//输出二维码
            out.flush();
		} catch (Exception e) {
			error("获取二维码出错，错误信息："+e);
			Result.outJson("参数异常", response);
		} finally{
			if(null != out){
				out.close();
			}
		}
	}
	
	private Map<String,Object> getParam(HttpServletRequest request){
		Map<String,Object> user = SessionUtils.getCurUser();
		/*long userTimes = (long) user.get("times");//判断及充值问题
		if(userTimes > NumberUtils.LONG_ZERO){
			throw new ValidateParamException(MsgConstants.MSG_CODE_3001,
					MsgConstants.MSG_CONTENT_3001, String.valueOf(userTimes));
		}*/
		String storeId = request.getParameter("storeId");
		if(!ValidatorUtils.isNumber(storeId)){
			throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
					MsgConstants.MSG_CONTENT_1002, "店铺");
		}
		String ruleId = request.getParameter("id");
		if(!ValidatorUtils.isNumber(ruleId)){
			throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
					MsgConstants.MSG_CONTENT_1002, "充值规则");
		}
		Map<String,Object> map = Maps.newHashMap();
		map.put("storeId", storeId);
		map.put("ruleId", ruleId);
		Map<String,Object> rule = rechargeRuleService.selectRechargeRule(map);
		if(null == rule || rule.isEmpty()){
			throw new ValidateParamException(MsgConstants.MSG_CODE_1002,
					MsgConstants.MSG_CONTENT_1002, "充值规则");
		}
		map.put("amount", rule.get("amount"));
		map.put("times", rule.get("times"));
		map.put("status", 0);
		map.put("userId", SessionUtils.getUserId());
		return map;
	}
	
	/**
	 * 充值列表
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "selectList", method = RequestMethod.GET)
	public Map<String, Object> selectList(HttpServletRequest request){
		Map<String,Object> map = this.initPaginationParams(request);
		map.put("userId", SessionUtils.getUserId());
		return MsgResult.okResultData(userRechargeService.selectRechargeByPage(map));
	}
	
}
